package com.project.mvprxsample.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.project.mvprxsample.bean.TestDB;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


/**
 * 数据库控制类
 * Created by lvyang on 2017/5/12.
 */
public class DataHelper extends OrmLiteSqliteOpenHelper {

    public static final String DATABASE_NAME = "SAMPLE.db";
    private static final int DATABASE_VERSION = 1;
    private static DataHelper mDataHelper;
    Map<String, Dao> mDaoMaps = null;

    public DataHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        initDaoMap();
    }

    public static DataHelper getDataHelper(Context context) {
        if (mDataHelper == null) {
            mDataHelper = new DataHelper(context);
        }
        return mDataHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, TestDB.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
        try {
            int upgradeVersion = oldVersion + 1;
            if (upgradeVersion == 2) {


                upgradeVersion = 3;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initDaoMap() {
        mDaoMaps = new HashMap<>();
        mDaoMaps.put("userInfo", null);

    }

    public Dao<TestDB, Integer> getUserInfo() {
        Dao<TestDB, Integer> userInfoDao = null;
        try {
            userInfoDao = mDaoMaps.get("userInfo");
            if (userInfoDao == null) {
                userInfoDao = getDao(TestDB.class);
                mDaoMaps.put("userInfo", userInfoDao);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return userInfoDao;
    }


}
